package cn.itcast.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet("/exportServlet")
public class ExportServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //告诉浏览器返回的数据类型,告诉浏览器数据的处理方式，作为附件下载
        response.setHeader("content-type",super.getServletContext().getMimeType(".txt"));
        response.setHeader("content-disposition","attachement;filename=user.txt");

        //读取储存的文件
        FileInputStream fis = new FileInputStream("D:/user.txt");
        ServletOutputStream sos = response.getOutputStream();
        byte[] arr = new byte[1024];
        int len;
        //将本地文件读取到浏览器
        while ((len=fis.read(arr))!=-1){
            sos.write(arr,0,len);
        }
        fis.close();

    }
}
